package admin

import (
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
	"net/http"
	"src/config"
	"src/model"
	"src/util/context"
	"src/util/log"
)

var admincommentLogger = log.GetLogger()

func writeadmincommentLoggerLoggerLog(funcName, errMsg string, err error) {
	admincommentLogger.WithFields(logrus.Fields{
		"package":  config.LogMessage + "/admin",
		"file":     "comment.go",
		"function": funcName,
		"err":      err,
	}).Warn(errMsg)
}

func DeleteComment(c echo.Context) error {
	comment := model.Comment{}
	err := c.Bind(&comment)

	if err != nil {
		writeadmincommentLoggerLoggerLog("DeleteComment", "1", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	id := context.GetJWTUsername(c)
	_, err = model.FindAdmin(id)
	if err != nil {
		writeadmincommentLoggerLoggerLog("DeleteComment", "2", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.Hasnotpower)
	}

	comment, err = model.DeleteComment(comment.ID.Hex(), comment.UserID, true)
	if err != nil {
		writeadmincommentLoggerLoggerLog("DeleteComment", "3", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorCommentDelete)
	}

	err = model.UpdateForumpostReply(comment.ForumpostId, -1)
	if err != nil {
		writeadmincommentLoggerLoggerLog("DeleteComment", "4", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorForumpostDelete)
	}

	reply := []model.Reply{}
	reply, err = model.GetReplyByCommentALL(comment.ID.Hex())
	if err != nil {
		writeadmincommentLoggerLoggerLog("DeleteComment", "5", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorReplyGet)
	}
	for i := 0; i < len(reply); i++ {
		_, _ = model.DeleteReply(reply[i].ID.Hex(), reply[i].UserID, true)
	}
	err = model.UpdateForumpostScore(comment.ForumpostId, -config.CommentScore)
	if err != nil {
		writeadmincommentLoggerLoggerLog("DeleteComment", "6", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorUpdateForumpostScore)
	}
	return context.RetData(c, "")
}
